import React, { useEffect } from "react";
import { Modal } from "antd";
import ms from "ms";

import useLogout from "../hooks/useLogout";

const IdleTimer = ({ children }) => {
  const { handleLogout } = useLogout();

  useEffect(() => {
    const signoutTime = ms("5m");
    const warningTime = ms("4.9m");
    let warnTimeout;
    let logoutTimeout;

    const events = [
      "load",
      "mousemove",
      "mousedown",
      "click",
      "scroll",
      "keypress"
    ];

    const warn = () => {
      Modal.warning({
        title: "登录超时警告",
        content: "您的登录状态已超时，请重新登录！",
        onCancel: handleLogout,
        onOk: handleLogout
      });
    };

    const setTimeouts = () => {
      warnTimeout = setTimeout(warn, warningTime);
      logoutTimeout = setTimeout(handleLogout, signoutTime);
    };

    const clearTimeouts = () => {
      if (warnTimeout) clearTimeout(warnTimeout);
      if (logoutTimeout) clearTimeout(logoutTimeout);
    };

    const resetTimeout = () => {
      clearTimeouts();
      setTimeouts();
    };

    for (let i in events) {
      window.addEventListener(events[i], resetTimeout);
    }

    setTimeouts();

    return () => {
      for (let i in events) {
        window.removeEventListener(events[i], resetTimeout);
        clearTimeouts();
      }
    };
  });

  return <>{children}</>;
};
export default IdleTimer;
